package in.rinisoft.sonar.maven.plugin;

import java.io.IOException;
import java.util.Collections;
import java.util.List;

import org.apache.maven.RepositoryUtils;
import org.apache.maven.artifact.repository.DefaultRepositoryRequest;
import org.apache.maven.artifact.repository.RepositoryRequest;
import org.apache.maven.execution.MavenSession;
import org.apache.maven.model.Plugin;
import org.apache.maven.plugin.MavenPluginManager;
import org.apache.maven.plugin.Mojo;
import org.apache.maven.plugin.MojoExecution;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.descriptor.MojoDescriptor;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.configuration.PlexusConfiguration;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.sonatype.aether.graph.DependencyFilter;
import org.sonatype.aether.graph.DependencyNode;
import org.sonatype.aether.repository.RemoteRepository;

/**
 * Code has been taken from Codehaus Sonar plugin and modified to suit the
 * needed whereever needed
 * 
 * @author Neeraj Mittal 
 */
public class Bootstraper {
	private MavenPluginManager pluginManager;

	public Bootstraper(MavenPluginManager pluginManager) {
		this.pluginManager = pluginManager;
	}

	public void start(MavenProject project, MavenSession session)
			throws IOException, MojoExecutionException {
		executeMojo(project, session);
	}

	@SuppressWarnings("unchecked")
	private void executeMojo(MavenProject project, MavenSession session)
			throws MojoExecutionException {
		ClassLoader originalClassLoader = Thread.currentThread()
				.getContextClassLoader();
		try {
			RepositoryRequest repositoryRequest = new DefaultRepositoryRequest();
			repositoryRequest.setLocalRepository(session.getLocalRepository());
			repositoryRequest.setRemoteRepositories(project
					.getPluginArtifactRepositories());

			Plugin plugin = createSonarPlugin();

			List<RemoteRepository> remoteRepositories = RepositoryUtils
					.toRepos(session.getCurrentProject()
							.getPluginArtifactRepositories());

			PluginDescriptor pluginDescriptor = this.pluginManager
					.getPluginDescriptor(plugin, remoteRepositories,
							session.getRepositorySession());

			String goal = "sonar-impl";

			MojoDescriptor mojoDescriptor = pluginDescriptor.getMojo(goal);
			if (mojoDescriptor == null) {
				throw new MojoExecutionException("Unknown mojo goal: " + goal);
			}
			MojoExecution mojoExecution = new MojoExecution(plugin, goal,
					"sonar" + goal);

			mojoExecution.setConfiguration(convert(mojoDescriptor));

			mojoExecution.setMojoDescriptor(mojoDescriptor);

			DependencyFilter artifactFilter = new DependencyFilter() {
				public boolean accept(DependencyNode arg0,
						List<DependencyNode> arg1) {
					return true;
				}
			};
			this.pluginManager.setupPluginRealm(pluginDescriptor, session,
					Thread.currentThread().getContextClassLoader(),
					Collections.<String> emptyList(), artifactFilter);

			Mojo mojo = (Mojo) this.pluginManager.getConfiguredMojo(Mojo.class,
					session, mojoExecution);
			Thread.currentThread().setContextClassLoader(
					pluginDescriptor.getClassRealm());
			mojo.execute();
		} catch (Exception e) {
			throw new MojoExecutionException("Can not execute Sonar", e);
		} finally {
			Thread.currentThread().setContextClassLoader(originalClassLoader);
		}
	}

	private Xpp3Dom convert(MojoDescriptor mojoDescriptor) {
		Xpp3Dom dom = new Xpp3Dom("configuration");

		PlexusConfiguration c = mojoDescriptor.getMojoConfiguration();

		PlexusConfiguration[] ces = c.getChildren();

		if (ces != null) {
			for (PlexusConfiguration ce : ces) {
				String value = ce.getValue(null);
				String defaultValue = ce.getAttribute("default-value", null);
				if ((value != null) || (defaultValue != null)) {
					Xpp3Dom e = new Xpp3Dom(ce.getName());
					e.setValue(value);
					if (defaultValue != null) {
						e.setAttribute("default-value", defaultValue);
					}
					dom.addChild(e);
				}
			}
		}

		return dom;
	}

	private Plugin createSonarPlugin() throws IOException {
		Plugin plugin = new Plugin();
		plugin.setGroupId("com.googlecode.sonar-multilang-maven-plugin");
		plugin.setArtifactId("sonar-multilang-maven-plugin");
		plugin.setVersion("1.0.0");
		return plugin;
	}
}
